<template>

    <a-modal v-model:visible="visible" :unmount-on-close="true" :title="name + '修改密码'" draggable
             @cancel="handleCancel" @before-ok="handleOk" :width="500">
        <a-form ref="formRef" :model="form">

            <a-form-item field="password" label="新密码" :rules="[{required:true,message:'请输入密码'}]">
                <a-input-password v-model="form.password" placeholder="请输入密码"/>
            </a-form-item>

            <a-form-item field="password2" label="确认密码" :rules="[{required:true,message:'请再次输入密码'}]">
                <a-input-password v-model="form.password2" placeholder="请再次输入密码"/>
            </a-form-item>

        </a-form>
    </a-modal>


</template>

<script setup lang="ts">

import {reactive, ref} from "vue";
import {doQuery} from "../../../scripts/mapper";
import {QueryResult} from "../../../scripts/type";
import {Message} from "@arco-design/web-vue";

const visible = ref(false);
const formRef = ref();
let name;

const emits = defineEmits(['done'])

let form = reactive({
    password: undefined,
    password2: undefined
})

const open = (username) => {
    name = username;
    form = reactive({
        password: undefined,
        password2: undefined
    })
    visible.value = true
}

const handleCancel = () => {
    visible.value = false
}

const handleOk = (done) => {
    formRef.value.validate((errors) => {
        if (!errors) {
            if (form.password !== form.password2) {
                Message.error("两次密码输入不一致");
                done(false)
                return
            }
            doQuery(`ALTER USER ${name} PASS '${form.password}';`).then((queryResult: QueryResult) => {
                if (queryResult.success && queryResult.data) {
                    Message.success("密码修改成功");
                    emits('done')
                    done()
                } else {
                    Message.error("密码修改失败" + (queryResult.message ? (": " + queryResult.message) : ""))
                }
            })
        } else {
            done(false)
        }
    })
}

defineExpose({
    open
})


</script>

<style scoped>

</style>
